package es.ats.codington.festival.servlets;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import es.ats.codington.festival.domain.Visitor;
import es.ats.codington.festival.services.VisitorService;

public class LoginServlet {

	public String process(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		String urlDispatcher = ""; 
		try {
			HttpSession sesion = request.getSession();
			
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			
			Visitor visitor = new Visitor();
			VisitorService vs = new VisitorService();
			
			//Esto no se para que cojones vale
			//ServletContext context = request.getServletContext();
		
			visitor.setUserName(username);
			visitor.setPassword(password);

			//If the visitor not exits
			if(vs.login(visitor) == 0)
			{
				request.setAttribute("error", "Login incorrecto.");
				urlDispatcher = "index.jsp";
			}		
			//if the visitor exits
			else{
				sesion.setAttribute("username", visitor.getUserName());
				sesion.setAttribute("peopleId", visitor.getPeopleId());
				sesion.setAttribute("isAdmin", visitor.getAdmin());
				
				if(visitor.getAdmin())
				{
					urlDispatcher = "WEB-INF/views/welcome.jsp";
					urlDispatcher = "WEB-INF/views/welcome_admin.jsp";
				}
				else
				{
					urlDispatcher = "WEB-INF/views/welcome.jsp";
				}
			}
		} catch (Exception e) {
			request.setAttribute("error", "Login incorrecto.");
			urlDispatcher = "index.hmtl";
		}		
		return urlDispatcher;
	}
	
	
	
}
